<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>账号数据管理</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form
        inline
        class="m-form--filter"
      >
        <el-form-item>
          <el-date-picker
            class="u-w330"
            size="mini"
            v-model="dateValue"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateChange"
            format="yyyy/MM/dd"
            :clearable="false"
            :picker-options="$store.state.PICKER_OPTIONS"

          >
          </el-date-picker> 
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择数据状态"
            v-model="filter.status"
          >
            <el-option
              v-for="item in STATEDATA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <br/>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择客户名称"
            v-model="filter.customerId"
            @change="handleChangeCustomerOptions"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择产品"
            v-model="filter.productId"
            @change="handleChangeProductOptions"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择平台"
            v-model="filter.platformId"
            @change="handleChangePlatformOptions"
          >
            <el-option
              v-for="item in platformOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w200"
            size="mini"
            filterable
            multiple
            collapse-tags
            placeholder="请选择账号ID"
            v-model="filter.usernameId"
            autocomplete="on"
          >
            <el-option
              v-for="(item, index) in usernameOptions"
              :key="index"
              :label="`${item.name}${item.accountName ? `(${item.accountName}`: ''}${item.id ? `,${item.id})` : ''}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格操作 -->
      <el-form
        inline
        class="m-table--handle"
      >
        <el-form-item>
            <ImportTable :importName="importName" :importUrl="importUrl"></ImportTable>
        </el-form-item>
        <el-form-item>
          <el-button
              @click="exportExcel('/manage/api/bus/account_data/export',requestSearch)"
              size="mini"
            >导出</el-button>
        </el-form-item>
        <el-form-item>
           <el-button
            size="mini"
            @click="handleDelete()"
          >删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" :underline="false" @click="downloadTemplate">下载导入模版</el-link> 
        </el-form-item>
        <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
        @selection-change="changeTableSelection"
      >
        <el-table-column
          type="selection"
          width="35"
          fixed
          :selectable="handleSelectable"
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
        >
          <el-table-column
            :resizable="false"
            align="center"
            :label="item.prop === 'reportTime' ? '总计' : getTableDataSumValue(item.prop, {rate: ['rebates']})"
            :prop="item.prop"
            :width="item.prop === 'reportTime' && 110"
            class-name="u-table--total"
          >

            <template slot-scope="scope">
               <!-- 账号名称 -->
              <template v-if="item.prop === 'accountName'">{{scope.row.accountName == ''|| scope.row.accountName == null ? '-' : scope.row.accountName}}</template>
              <!-- 服务费率 -->
              <template v-else-if="item.prop === 'serviceRate'">{{scope.row.serviceRate + '%'}}</template>
              <!-- 当前返点 -->
              <template v-else-if="item.prop === 'rebates'">{{scope.row.rebates + '%'}}</template>
              <!-- 是否启用 -->
              <template v-else-if="item.prop === 'status'">{{scope.row.status === 1 ? "未生成结算单" : "已生成结算单"}} </template>
              <!-- 其他 -->
              <template v-else>{{scope.row[item.prop]}}</template>
            </template>

          </el-table-column>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="[50, 100, 500, 1000]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="pageTotal"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
    </Container>
  </div>
</template>

<script>
// import Moment from "moment";
import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";
import ImportTable from "@/components/import-table.vue";

import { STATEDATA,OPERATOR_OPTION, CUSTOMER_ROLE_OPTION } from "@/assets/js/flow-option";
import { mapOptionLabel } from "@/util";
import { exportExcel } from '@/utils/fileDown.js'

export default {
  name: "flow-accountdata",
  components: {
    Container,
    CustomTableColumn,
    ImportTable
  },
  data() {
    return {
      OPERATOR_OPTION,
      STATEDATA,
      CUSTOMER_ROLE_OPTION,
      BASE_URL: process.env.VUE_APP_BASE_URL,
      fileList:[],
      // 下拉
      dateValue:Number(this.$route.query.dataValue)|| [],
      customerOptions: [],
      productOptions: [],
      platformOptions: [],
      usernameOptions: [],
      // 筛选
      filter: {
        startDate: '',
        endDate:'',
        businessId:null,
        status: Number(this.$route.query.status) || null,
        customerId: Number(this.$route.query.customerId) || null,
        productId: Number(this.$route.query.productId) || null,
        platformId: Number(this.$route.query.platformId) || null,
        usernameId: [null],
        operator: null
      },
      // 导入
      importName:'导入',
      importUrl:'/manage/api/bus/account_data/uploadflie',

      tableData: [],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "日期（天）",
          prop: "reportTime",
          visible: true
        },
        {
          label: "客户名称",
          prop: "customerName",
          visible: true
        },
        {
          label: "产品名称",
          prop: "productName",
          visible: true
        },
        {
          label: "平台名称",
          prop: "platformName",
          visible: true
        },
        {
          label: "登陆账号",
          prop: "username",
          visible: true
        },
        {
          label: "账号名称",
          prop: "accountName",
          visible: true
        },
        {
          label: "账号ID",
          prop: "usernameId",
          visible: true
        },
        {
          label: "当日返点",
          prop: "rebates",
          visible: true
        },
        {
          label: "当日消耗（元）",
          prop: "consum",
          visible: true
        },
        {
          label: "激励消耗（元）",
          prop: "incentiveConsum",
          visible: true
        },
        {
          label: "折后消耗（元）",
          prop: "afterDiscountConsum",
          visible: true
        },
        {
          label: "服务费率",
          prop: "serviceRate",
          visible: true
        },
        {
          label: "数据状态",
          prop: "status",
          visible: true
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 50
      },
      pageTotal: 0
    };
  },
  computed: {
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    requestSearch() {
      return {
        ...this.filter,
        ...this.page,
        usernameId: this.filter.usernameId.includes(null)
          ? null
          : this.filter.usernameId.join()
      };
    }
  },
  methods: {
    exportExcel,
    /* 获取过去时间，并传值给现在时间 */
    getPassYearFormatDate () {
      var nowDate = new Date()
      var date = new Date(nowDate)
      date.setDate(date.getDate() - 365)
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var formatDate = year + seperator1 + month + seperator1 + strDate
      this.getNowFormatDate(formatDate)
    },
    /* 获取现在时间，并接受过去时间的值 */
    getNowFormatDate (formatDate) {
          var date = new Date()
          var seperator1 = '-'
          var year = date.getFullYear()
          var month = date.getMonth() + 1
          var strDate = date.getDate()
          if (month >= 1 && month <= 9) {
            month = '0' + month
          }
          if (strDate >= 0 && strDate <= 9) {
            strDate = '0' + strDate
          }
          var nowData = year + seperator1 + month + seperator1 + strDate
          this.dateValue= [formatDate, nowData]  // 默认赋值一年时间
          this.filter.startDate = formatDate
          this.filter.endDate = nowData
    },
    // 下载模板
    downloadTemplate() {
      location.href = "https://s.55duanzi.com/CMS/账号数据导入表格.xls";
    },
    // 导出业务清单
    dateChange() {
      this.filter.startDate = this.formatDateTime(this.dateValue[0], "y-m-d");
      this.filter.endDate = this.formatDateTime(this.dateValue[1], "y-m-d");
    },
    mapOptionLabel,

    // 下拉
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = [
            {
              id: null,
              name: "全部客户"
            }
          ].concat(res.data.data);
          if (this.$route.query.customerId) {
            this.filter.customerId = Number(this.$route.query.customerId);
          }
        }
      });
    },
    fetchProductOptions(customerId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_no_stop_product",
        params: { platformId:0,customerId: Number(customerId) }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = [
            {
              id: null,
              name: "全部产品"
            }
          ].concat(res.data.data);
          if (this.$route.query.productId) {
            this.filter.productId = Number(this.$route.query.productId);
          }
        }
      });
    },
    fetchPlatformOptions(customerId = 0, productId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 0,
          customerId: Number(customerId),
          productId: Number(productId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = [
            {
              id: null,
              name: "全部平台"
            }
          ].concat(res.data.data);
          if (this.$route.query.platformId) {
            this.filter.platformId = Number(this.$route.query.platformId);
          }
        }
      });
    },
    fetchUsernameOptions(customerId = 0, productId = 0, platformId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/account/get_username_id_list",
        params: {
          customerId: Number(customerId),
          productId: Number(productId),
          platformId: Number(platformId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.usernameOptions = [
            {
              id: null,
              name: "全部账号ID"
            }
          ].concat(res.data.data);
        }
      });
    },
    handleChangeCustomerOptions() {
      this.filter.productId = null;
      this.filter.platformId = null;
      this.filter.usernameId = [null];
      this.fetchProductOptions(this.filter.customerId);
    },
    handleChangeProductOptions() {
      this.filter.platformId = null;
      this.filter.usernameId = [null];
      this.fetchPlatformOptions(this.filter.customerId, this.filter.productId);
    },
    handleChangePlatformOptions() {
      this.filter.usernameId = [null];
      this.fetchUsernameOptions(this.filter.customerId, this.filter.productId, this.filter.platformId);
    },

    addOperate() {
      this.dialogOperateData.operate.push({ operatorBy: "", startDate: "" });
    },
    removeOperate(index) {
      this.dialogOperateData.operate.splice(index, 1);
    },
    // 列表
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    //获取列表
    getTable() {
      this.$http({
        method: "post",
        url: "/manage/api/bus/account_data/get_list",
        data: {
          ...this.filter,
          ...this.page,
          usernameId: this.filter.usernameId.includes(null)
            ? null
            : this.filter.usernameId.join()
        }
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          if(data.list.length == 0){
            this.tableData = data.list
          }else{
            this.tableData = this.modTableDataSumList(
              data.sumList,
              data.list
            );
          }
          this.pageTotal = data.listCount;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return value
        }
        return String(value);
      }
      return "";
    },
    // 删除数据
    handleDelete() {
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要删除的选项！");
      }
      this.removeData(
        this.tableSelectionData.map(item => item.id).join()
      );
    },
    removeData(id) {
      this.$confirm("是否删除此账号？删除后不可恢复！", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
           this.$http({
            method: "post",
            url: "/manage/api/bus/account_data/del",
            params: {
              ids: id
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("删除成功!");
              this.getTable();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //判断选择框是否可选
    handleSelectable(row) {
      return row.status == 1 ? true :false ;
    },
    changeTableSelection(data) {
      this.tableSelectionData = data;
    },
    handlePagerSizeChange(v) {
      this.page.pageSize = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.page.pageNo = v;
      this.getTable();
    }
  },
  activated(){
    this.getTable();
  },
  created() {
    this.getPassYearFormatDate ()
    this.fetchCustomerOptions();
    this.fetchProductOptions();
    this.fetchPlatformOptions();
    this.fetchUsernameOptions();
  }
};
</script>
<style scoped lang="scss">
  .dialog{
    margin-left:100rpx;
    div{
      margin-bottom:10px;
    }
  }
  .msg{
    margin-left:50px;
  }
</style>